<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.model == 'bankName' || item.model == 'WorkFlowStatus'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="c_index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table.beautiful-table-double(:columns="setThead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |费用月份：
              span.text-info.pl-5.pr-5.font-weight {{$moment(salaryMonth).format('YYYY年MM月')}}
              Divider(type="vertical")
              |客户名称：
              span.text-info.pl-5.pr-5.font-weight {{customerName}}
              br
              div(style='line-height:20px')
                //- Divider(type="vertical")
                |客户法定名称：
                span.text-info.pl-5.pr-5.font-weight {{legalName}}
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasPaied" type="info" @click="handleShowSendConfirmModal" :disabled="selectedId.length == 0") 确认发放
              Button.mr-10(v-if="hasImportResult" type="info" @click="handleShowBatchImportModal") 导入发放结果
              Button.mr-10(v-if="hasReject" type="info" @click="handleShowSendBackModalB" :disabled="selectedId.length == 0") 驳回
              Button.mr-10(v-if="hasBack" type="info" @click="handleShowSendBackModal" :disabled="selectedId.length == 0") 退回
              Button.mr-10(v-if="hasExportGrantData" type="info" @click="handleShowChooseBankModal") 导出发放表
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action_hasWorkFlow")
            Button.mr-10(type="text" size="small" @click="handleShowAuditDetailModal(row)" :disabled="!row.workFlowStatus") 查看审批详情
            Button.mr-10(type="text" size="small" @click="handleDownLoadAttachment(row)" :disabled="!(row.attachmen && row.attachmen.path)") 附件下载
            Button(type="text" size="small" @click="handleDownLoadPayAttachmen(row)" :disabled="!(row.payAttachmen && row.payAttachmen.path)") 付款反馈下载
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(type="text" size="small" @click="handleDownLoadAttachment(row)" :disabled="!(row.attachmen && row.attachmen.path)") 附件下载
            Button(type="text" size="small" @click="handleDownLoadPayAttachmen(row)" :disabled="!(row.payAttachmen && row.payAttachmen.path)") 付款反馈下载

    //- 导入弹窗
    BatchImportModal(ref="BatchImportModal" @query="searchFn")
    //- 退回弹窗
    SendBackModal(ref="SendBackModal" @query="searchFn")
    //- 选择银行
    ChooseBankModal(ref="ChooseBankModal" @query="searchFn")
    //- 确认弹窗
    SendConfirmModal(ref="SendConfirmModal" @query="searchFn")
    //- 流程审批单弹窗
    AuditDetailModal(ref="AuditDetailModal" @query="query")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinanceSPayableApi } from '@/api/FinanceSPayable.api.js'
import { OrganizationBankApi } from "@/api/OrganizationBank.api.js"
import { FinanceSalaryApi } from "@/api/FinanceSalary.api.js"
import { SalaryDetailThead } from "./tableHead.js"
import _cloneDeep from "clone-deep"
import SendBackModal from "./modal/SendBackModal.vue"
import { EmployeesApi } from "@/api/Employees.api.js"
import BatchImportModal from "./modal/BatchImportModal.vue"
import SendConfirmModal from "./modal/SendConfirmModal.vue"
import ChooseBankModal from "./modal/ChooseBankModal.vue"
import AuditDetailModal from "../publicModal/auditDetailModal.vue"

export default {
  name: "",

  components: {
    BatchImportModal,
    ChooseBankModal,
    SendConfirmModal,
    SendBackModal,
    AuditDetailModal
  },

  data() {
    return {
      companyId: "", // 公司ID
      customerName: "", // 公司名称
      legalName: '', // 公司法定名称
      salaryMonth: "",
      // thead: _cloneDeep(SalaryDetailThead),
      tableColumns: _cloneDeep(SalaryDetailThead),
      thead: ['selection', 'name', 'idCardNO', 'bankName', 'accountNo', 'accountName', 'phone', 'shouldSalaryTotal', 'socialSecurityDeduct', 'providentFundDeduct', 'otherDeduct', 'incomeDeduct', 'serviceCharge', 'realSalaryTotal', 'status', 'remark', 'backTime', 'payUser', 'payTime', 'action'],
      thead_hasWorkFlow: ['selection', 'batchID', 'name', 'idCardNO', 'bankName', 'accountNo', 'accountName', 'phone', 'shouldSalaryTotal', 'socialSecurityDeduct', 'providentFundDeduct', 'otherDeduct', 'incomeDeduct', 'serviceCharge', 'realSalaryTotal', 'status', 'remark', 'backTime', 'payUser', 'payTime',  'workFlowStatus', 'action_hasWorkFlow'],
      tableData: [],
      formData: {
        employeeName: null,
        iDCardNo: null,
        bankName: null,
        status: null,
        WorkFlowStatus: null,
      },
      formItem: [
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'employeeName', model: 'employeeName', style: 'ivu-col-span-8' },
        { type: 'input', label: '身份证号码：', placeholder: '请输入身份证号码', prop: 'iDCardNo', model: 'iDCardNo', style: 'ivu-col-span-8' },
        { type: 'select', label: '工资发放银行：', placeholder: '请输入工资发放银行', prop: 'bankName', model: 'bankName', options: 'bankList', style: 'ivu-col-span-8' },
        { type: 'select', label: '发放状态：', placeholder: '请输入发放状态', prop: 'status', model: 'status', options: 'status', style: 'ivu-col-span-8' },
        { type: 'select', label: '审批结果：', placeholder: '请输入审批结果', prop: 'WorkFlowStatus', model: 'WorkFlowStatus', options: 'workflowstatus', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-8' }
      ],
      rules: {},
      selectedId: [], // 勾选的id集合,array格式
      selectedArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0 // 合计
      },
      downLoadRul: "",
      arrListDown: {
        status: [
          // {label: '待申请', value: '1'},
          // // {label: '已申请', value: '2'},
          // {label: '已付款', value: '3'},
          // {label: '待付款', value: '4'}
        ],
        bankList: [],
        bankListExport: [],
        workflowstatus: []
      },
      datePickerDefault: new Date(), // 当前时间
    };
  },

  watch: {},

  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    setThead () {
      if (this.isWorkFlow) {
        return Common.getTableColumns(this.thead_hasWorkFlow, this.tableColumns)
      } else {
        return Common.getTableColumns(this.thead, this.tableColumns)
      }
    },

    setFormItem() {
      if (this.isWorkFlow) {
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 4), ...this.formItem.slice(5, this.thead.length + 1)]
      }
    },

    actionArr() {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code;
      });
      return arr;
    },
    // 个税付款确认
    hasToPostIncome() {
      return this.actionArr.indexOf("ToPostIncome") > -1;
    },
    // 导出
    hasExportAll() {
      return this.actionArr.indexOf("ExportAll") > -1;
    },
    // 退回
    hasBack() {
      return this.actionArr.indexOf("Back") > -1;
    },
    // 驳回
    hasReject() {
      return this.actionArr.indexOf("Reject") > -1;
    },
    // 明细
    hasGetDetails() {
      return this.actionArr.indexOf("GetDetails") > -1;
    },
    // 导出明细
    hasExportApplyDetail() {
      return this.actionArr.indexOf("ExportApplyDetail") > -1;
    },
    // 导入发放结果
    hasImportResult() {
      return this.actionArr.indexOf("ImportResult") > -1;
    },
    // 确认发放
    hasPaied() {
      return this.actionArr.indexOf("Paied") > -1;
    },
    // 导出发放表
    hasExportGrantData() {
      return this.actionArr.indexOf("ExportGrantData") > -1;
    },
  },

  
  mounted() {
    this.companyId = this.$route.query.companyId
    this.customerName = this.$route.query.customerName
    this.legalName = this.$route.query.legalName
    this.salaryMonth = this.$route.query.salaryMonth
    this.getEnum()
    this.queryBankList()
    this.queryBankListExport()
    this.query()
  },

  methods: {
    // 数据字典
    getEnum () {
      let groupName = 'financesalary.status,finance.workflowstatus'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 搜索
    searchFn() {
      this.tableComone.pageIndex = 1;
      this.query();
      this.queryBankListExport()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage(val) {
      this.tableComone.pageIndex = val;
      this.query();
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange(val) {
      this.tableComone.pageIndex = 1;
      this.tableComone.pageSize = val;
      this.query();
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        SalaryID: this.$route.query.salaryID,
        CompanyID: this.$route.query.companyID,
        SalaryMonth: this.$route.query.salaryMonth,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await FinanceSPayableApi.getDetails({...params, ...this.formData})
      console.log('详情res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        // this.tableData = res.data.data.map(item => {
        //   return {...item, _disabled: item.workFlowStatus == '已完成' && item.status == 2 ? false : true}
        // })
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
        this.selectedId = []
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange(value) {
      this.selectedArr = value.map(item => {
        return { id: item.salaryGUID, name: item.name, employeeGUID: item.employeeGUID, salaryBillID: item.salaryBillID };
      });
      this.selectedId = value.map(item => {
        return item.salaryGUID;
      });
      console.log("列表勾选数组1", this.selectedArr);
      console.log("列表勾选数组2", this.selectedId);
    },

    // 获取银行下拉
    async queryBankList () {
      var params = {
        HasPaging: true,
        PageIndex: 1,
        PageSize: 100
      }
      let res = await OrganizationBankApi.getList(params)
      console.log('获取银行下拉res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.bankList = res.data.data.map(item => {return {label: item.bankName, value: item.bankName}})
      } else {
        this.arrListDown.bankList = []
      }
      this.loading = false
    },

    // 获取银行下拉
    async queryBankListExport () {
      console.log('queryBankListExport')
      var params = {
        SalaryID: this.$route.query.salaryID,
        CompanyID: this.$route.query.companyID,
        SalaryMonth: this.$route.query.salaryMonth,
        HasPaging: true,
        PageIndex: 1,
        PageSize: 100,
      }
      let res = await FinanceSalaryApi.getGrantBankInfo({...params, ...this.formData})
      console.log('获取银行下拉res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.bankListExport = res.data.data.map(item => {return {label: `${item.accountName}(${item.realSalaryTotal}元)`, value: item.accountName}})
      } else {
        this.arrListDown.bankListExport = []
      }
      this.loading = false
    },

    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.show()
    },

    handleShowSendBackModalB (row) {
      // var employeeIDS = this.selectedArr.map(item => {return item.employeeGUID})
      var salaryBillIDS = this.selectedArr.map(item => {console.log(item,'back');return item.salaryBillID})
      this.$refs.SendBackModal.show(row, salaryBillIDS,4)
    },

    handleShowSendBackModal (row) {
      // var employeeIDS = this.selectedArr.map(item => {return item.employeeGUID})
      var salaryBillIDS = this.selectedArr.map(item => {console.log(item,'back');return item.salaryBillID})
      this.$refs.SendBackModal.show(row, salaryBillIDS,5)
    },

    handleShowSendConfirmModal (row) {
      // var employeeIDS = this.selectedArr.map(item => {return item.employeeGUID})
      var salaryBillIDS = this.selectedArr.map(item => {return item.salaryBillID})
      this.$refs.SendConfirmModal.show(row, salaryBillIDS)
    },

    handleShowChooseBankModal () {
      // var employeeIDS = this.selectedArr.map(item => {return item.employeeGUID})
      var salaryBillIDS = this.selectedArr.map(item => {return item.salaryBillID})
      this.$refs.ChooseBankModal.arrListDown = this.arrListDown
      this.$refs.ChooseBankModal.show(this.formData, salaryBillIDS)
    },

    // 是否发放前询问
    isPaiedModal () {
      this.$Modal.confirm({
        title: '是否确认发放',
        onOk: () => {
          this.handlePaied()
        }
      })
    },

    // 确认发放
    async handlePaied () {
      // var employeeIDS = this.selectedArr.map(item => {return item.employeeGUID})
      var salaryBillIDs = this.selectedArr.map(item => {return item.salaryBillID})
      var params = {
        SalaryID: this.$route.query.salaryID,
        SalaryMonth: this.$route.query.salaryMonth,
        SalaryBillIDs: salaryBillIDs
        // EmployeeIDs: employeeIDS
      }
      let res = await FinanceSPayableApi.paied(params)
      console.log('确认发放res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query();
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    
    // 流程审批单-显示弹窗
    handleShowAuditDetailModal(row) {
      console.log('流程审批单-显示弹窗 row: ', row)
      this.$refs.AuditDetailModal.modalType = '薪资审批详情'
      this.$refs.AuditDetailModal.show(row)
    },

    // 附件下载
    handleDownLoadAttachment (row) {
      if (row.attachmen && row.attachmen.path) {
        let str = row.attachmen.path
        console.log('附件下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },

    // 付款反馈下载
    handleDownLoadPayAttachmen (row) {
      if (row.payAttachmen && row.payAttachmen.path) {
        let str = row.payAttachmen.path
        console.log('付款反馈下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },
  } // methods end
}
</script>

<style lang="less" scoped>
</style>
